<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               ref="crud"
               v-model="form"
               :permission="permissionList"
               :before-open="beforeOpen"
               @row-del="rowDel"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   v-if="permission.role_delete"
                   plain
                   @click="handleDelete">删 除
        </el-button>
        <el-button size="small"
                   icon="el-icon-setting"
                   @click="handleRole"
                   v-if="permission.role_permission"
                   plain>权限设置
        </el-button>
      </template>
    </avue-crud>
    
    <el-dialog 
      title="角色菜单权限配置"
      append-to-body
      :visible.sync="box"
      width="345px"
    >
      <el-tree 
        :data="menuGrantList"
        show-checkbox
        node-key="id"
        :props="{ label: 'name' }"
        ref="treeMenu"
        :default-checked-keys="menuTreeObj"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="box=false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
  import {add, getList, getRole, grant, grantTree, remove, update, getRoleTreeAPI} from "@/api/system/role";
  import {mapGetters} from "vuex";

  export default {
    data() {
      return {
        form: {},
        box: false,
        menuGrantList: [],
        apiGrantList: [],
        menuTreeObj: [],
        selectionList: [],
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        option: {
          height: 'auto',
          calcHeight: 21,
          tip: false,
          simplePage: true,
          searchShow: true,
          searchMenuSpan: 5,
          searchGutter: 10,
          tree: true,
          border: true,
          index: true,
          selection: true,
          viewBtn: true,
          dialogWidth: 900,
          dialogClickModal: false,
          searchLabelPosition: 'top',
          searchIcon: true,
          searchIndex: 3,
          searchMenuPosition: 'right',
          column: [
            {
              label: "角色名称",
              prop: "roleName",
              search: true,
              searchLabel: '',
              searchPlaceholder: '角色名称',
              span: 24,
              rules: [
                {
                  required: true,
                  message: "请输入角色名称",
                  trigger: "blur"
                }
              ]
            },
            {
              label: "角色别名",
              prop: "roleAlias",
              search: true,
              searchLabel: '',
              searchPlaceholder: '角色别名',
              span: 24,
              rules: [
                {
                  required: true,
                  message: "请输入角色别名",
                  trigger: "blur"
                }
              ]
            },
            {
              label: "上级角色",
              prop: "parentId",
              dicUrl: getRoleTreeAPI,
              props: {
                label: "roleName",
                value: "id"
              },
              type: "tree",
              hide: true,
              span: 24,
              rules: [
                {
                  required: false,
                  message: "请选择上级角色",
                  trigger: "click"
                }
              ]
            },
            {
              label: "角色排序",
              prop: "sort",
              type: "number",
              span: 24,
              rules: [
                {
                  required: true,
                  message: "请输入角色排序",
                  trigger: "blur"
                }
              ]
            }
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["userInfo", "permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.role_add, false),
          viewBtn: this.vaildData(this.permission.role_view, false),
          delBtn: this.vaildData(this.permission.role_delete, false),
          editBtn: this.vaildData(this.permission.role_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      },
      idsArray() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids;
      }
    },
    methods: {
      async submit() {
        const menuList = this.$refs.treeMenu.getCheckedKeys();
        await grant(this.ids, menuList)
        this.box = false;
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        this.onLoad(this.page);
      },
      async rowSave(row, done, loading) {
        try {
          var { data } = await add(row)
        } finally {
          loading();
        }
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        row.id = data
        done(row);
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },

      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      beforeOpen(done, type) {
        if (["add", "edit"].includes(type)) {
          // 更新字典
          this.$refs.crud.updateDic('parentId')
        }
        done();
      },
      async handleRole() {
        if (this.selectionList.length !== 1) {
          this.$message.warning("只能选择一条数据");
          return;
        }
        this.menuTreeObj = [];
        var { data } = await grantTree()
        this.menuGrantList = data;
        var { data } = await getRole(this.ids)
        this.menuTreeObj = data;
        this.box = true;
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      currentChange(currentPage) {
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      async onLoad(page, params = {}) {
        this.loading = true;
        const { data } = await getList(page.currentPage, page.pageSize, Object.assign(params, this.query))
        this.data = data;
        this.loading = false;
        this.selectionClear();
      }
    }
  };
</script>
